import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import api from './api';
import type { Snippet } from './snippetTypes';

function SnippetList() {
  const [snippets, setSnippets] = useState<Snippet[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchSnippets();
  }, []);

  const fetchSnippets = async () => {
    try {
      // ✅ 添加 /api 前缀，匹配后端接口路径
      const response = await api.get<Snippet[]>('/snippets'); 
      setSnippets(response.data);
      setLoading(false);
    } catch (error) {
      console.error('获取代码片段失败:', error);
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (window.confirm('确定要删除吗?')) {
      try {
        // ✅ 添加 /api 前缀，匹配后端接口路径
        await api.delete(`/snippets/${id}`); 
        fetchSnippets();
      } catch (error) {
        console.error('删除失败:', error);
      }
    }
  };

  if (loading) return <div>加载中...</div>;

  return (
    <div>
      <h2>代码片段列表</h2>
      <div className="snippet-list">
        {snippets.map(snippet => (
          <div key={snippet.id} className="snippet-item">
            <h3>{snippet.title}</h3>
            <div className="actions">
              <Link to={`/snippets/${snippet.id}`} className="btn">查看</Link>
              <Link to={`/snippets/edit/${snippet.id}`} className="btn">编辑</Link>
              <button 
                onClick={() => handleDelete(snippet.id)}
                className="btn danger"
              >
                删除
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default SnippetList;